-- cmd_buy_device_material
-- Create by dengc
-- 购买装置材料

function Operation.cmd_buy_device_material(id, num)
    -- 客户端先自己购买
    local price = ItemM.query(id, "buy_price");
    if type(price) ~= "table" or #price <= 0 then
        return;
    end
    price = price[1];

    if price[1] == 1 then
        -- 物品
        local classId = price[2];
        local amount = price[3] * num;

        -- 数量不足
        if ItemM.getAmount(ME.user, classId) < amount then
            return;
        end

        -- 扣除
        ItemM.costAmount(ME.user, classId, amount);
    elseif price[1] == 2 then
        -- 属性
        local attrib = price[2];
        local amount = price[3] * num;
        if ME.user:queryAttrib(attrib) < amount then
            return;
        end

        -- 扣除属性
        ME.user:costAttrib(attrib, amount);
    end

    -- 奖励
    BonusM.doBonus({ 1, id, num }, "buy_material");

    -- 抛出事件
    EventMgr.fire(event.BUY_DEVICE_MATERIAL, { ["classId"] = id, ["amount"] = num });

    local v = {
        ["material_id"] = id,
        ["amount"]      = num,
    };

    SyncM.addMessage("CMD_BUY_DEVICE_MATERIAL", v);

    -- 同步
    SyncM.startSync();
end
